package com.ruicar.afs.cloud.contract.gateway.processor.api;

import cn.hutool.json.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.contract.gateway.beans.ApiDefine;
import com.ruicar.afs.cloud.contract.gateway.beans.GateWayResponse;
import com.ruicar.afs.cloud.contract.gateway.components.ProcessorCache;
import com.ruicar.afs.cloud.contract.gateway.entity.GateWayApiMapping;
import com.ruicar.afs.cloud.contract.gateway.enums.ProcessorName;
import com.ruicar.afs.cloud.contract.gateway.service.GateWayApiMappingService;
import com.ruicar.afs.cloud.manage.api.feign.gateway.ContractGateWayManageCall;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysAddressParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description:
 */
@Component
@Slf4j
@AllArgsConstructor
public class CCSInterfaceProcessor implements ApiProcessor {
    private final ContractGateWayManageCall contractGateWayManageCall;
    private final GateWayApiMappingService gateWayApiMappingService;
    private final DefaultApiProcessor defaultApiProcessor;
    final static JSONObject jsonbSuccess = new JSONObject();
    final static JSONObject jsonbError = new JSONObject();
    static{
        jsonbSuccess.put("resultCode","0000");
        jsonbSuccess.put("resultData","");
        jsonbSuccess.put("timestamp","");
        jsonbSuccess.put("signcode","");
    }

    static{
        jsonbError.put("resultCode","0001");
        jsonbError.put("resultData","接口请求异常");
        jsonbError.put("timestamp","");
        jsonbError.put("signcode","");
    }
    @Override
    public ProcessorName processName() {
        return ProcessorName.CCS_INTERFACE;
    }

    @Override
    public GateWayResponse process(JSON params, ApiDefine apiDefine) {
        GateWayApiMapping gateWayApiMapping = convertUri(params);
        if(ObjectUtils.isEmpty(gateWayApiMapping)){
            return new GateWayResponse(jsonbError.toJSONString());
        }
        ApiDefine define  = ProcessorCache.getApiDefine(gateWayApiMapping);
        JSON json = params.getByPath("data", JSON.class);
        GateWayResponse process = defaultApiProcessor.process(json, define);
        JSONObject jsonObject = JSONObject.parseObject(process.getData());
        if(jsonObject.containsKey("code")){
            if(CommonConstants.FAIL.equals(jsonObject.getString("code"))){
                process.setData(jsonbError.toJSONString());
            }else{
                process.setData(jsonbSuccess.toJSONString());
            }
        }else {
            jsonObject.put("timestamp","");
            jsonObject.put("signcode","");
            if("getWorkOrder".equals(params.getByPath("code"))){
                workOrderProcessor(jsonObject);
            } else if("getRepaymentPlan".equals(params.getByPath("code"))){
                repaymentPlanProcessor(jsonObject);
            }else if("getCustomer".equals(params.getByPath("code"))){
                customerProcessor(jsonObject);
            }else if("getCustomerInfo".equals(params.getByPath("code"))){
                customerInfoProcessor(jsonObject);
            }
            else {
                jsonObject.put("resultData", com.alibaba.fastjson.JSON.toJSONString(jsonObject.get("resultData"), SerializerFeature.WriteMapNullValue));
            }

            if("{}".equals(jsonObject.getString("resultData"))){
                jsonObject.put("resultData", "");
            }
            process.setData(jsonObject.toJSONString());
        }
        return process;
    }


    /**
     * uri转换
     * @param params
     * @return
     */
    private GateWayApiMapping convertUri(JSON params){
        GateWayApiMapping gateWayApiMapping = null;
        if("getRepaymentPlan".equals(params.getByPath("code"))){
            gateWayApiMapping = gateWayApiMappingService.getOne(Wrappers.<GateWayApiMapping>lambdaQuery().eq(GateWayApiMapping::getApiUri, "/get_repayment_plan"));
        }else if("getCustomerInfo".equals(params.getByPath("code"))){
            gateWayApiMapping = gateWayApiMappingService.getOne(Wrappers.<GateWayApiMapping>lambdaQuery().eq(GateWayApiMapping::getApiUri, "/get_customer_info"));
        }else if("getCustomer".equals(params.getByPath("code"))){
            gateWayApiMapping = gateWayApiMappingService.getOne(Wrappers.<GateWayApiMapping>lambdaQuery().eq(GateWayApiMapping::getApiUri, "/get_customer"));
        }else if("getWorkOrder".equals(params.getByPath("code"))){
            gateWayApiMapping = gateWayApiMappingService.getOne(Wrappers.<GateWayApiMapping>lambdaQuery().eq(GateWayApiMapping::getApiUri, "/get_work_order"));
        }else if("getReceivable".equals(params.getByPath("code"))){
            gateWayApiMapping = gateWayApiMappingService.getOne(Wrappers.<GateWayApiMapping>lambdaQuery().eq(GateWayApiMapping::getApiUri, "/ccs/get_receivable"));
        }else if("getCMSRequest".equals(params.getByPath("code"))){
            gateWayApiMapping = gateWayApiMappingService.getOne(Wrappers.<GateWayApiMapping>lambdaQuery().eq(GateWayApiMapping::getApiUri, "/get_cms_request"));
        }else if("getContract".equals(params.getByPath("code"))){
            gateWayApiMapping = gateWayApiMappingService.getOne(Wrappers.<GateWayApiMapping>lambdaQuery().eq(GateWayApiMapping::getApiUri, "/ccs/get_contract"));
        }else if("loanSchedule".equals(params.getByPath("code"))){
            gateWayApiMapping = gateWayApiMappingService.getOne(Wrappers.<GateWayApiMapping>lambdaQuery().eq(GateWayApiMapping::getApiUri, "/ccs/loan_schedule"));
        }
        return gateWayApiMapping;
    }
    /**
     * 获取工单
     * 翻译地址信息
     * @param jsonObject
     */
    private void workOrderProcessor(JSONObject jsonObject){
        //翻译地址库
        JSONObject resultData = jsonObject.getJSONObject("resultData");
        if(ObjectUtils.isNotEmpty(resultData)){
            IResponse<TsysAddressParam> response1 = contractGateWayManageCall.translateAddress(resultData.getString("customer_city"));
            String customer_city = CommonConstants.SUCCESS.equals(response1.getCode())&&EmptyUtils.isNotEmpty(response1.getData())?response1.getData().getLabel():resultData.getString("customer_city");
            IResponse<TsysAddressParam> response2 = contractGateWayManageCall.translateAddress(resultData.getString("customer_province"));
            String customer_province = CommonConstants.SUCCESS.equals(response2.getCode())&&EmptyUtils.isNotEmpty(response2.getData())?response2.getData().getLabel():resultData.getString("customer_province");
            IResponse<TsysAddressParam> response3 = contractGateWayManageCall.translateAddress(resultData.getString("dealer_province"));
            String dealer_province = CommonConstants.SUCCESS.equals(response3.getCode())&&EmptyUtils.isNotEmpty(response3.getData())?response3.getData().getLabel():resultData.getString("dealer_province");
            IResponse<TsysAddressParam> response4 = contractGateWayManageCall.translateAddress(resultData.getString("dealer_city"));
            String dealer_city = CommonConstants.SUCCESS.equals(response4.getCode())&&EmptyUtils.isNotEmpty(response4.getData())?response4.getData().getLabel():resultData.getString("dealer_city");
            resultData.put("customer_city",customer_city);
            resultData.put("customer_province",customer_province);
            resultData.put("dealer_province",dealer_province);
            resultData.put("dealer_city",dealer_city);
            jsonObject.put("resultData", com.alibaba.fastjson.JSON.toJSONString(resultData, SerializerFeature.WriteMapNullValue));
        }
    }

    /**
     * 获取还款计划
     * 处理固定利率、浮动利率展示不同字段
     * @param jsonObject
     */
    private void repaymentPlanProcessor(JSONObject jsonObject){
        //判断是否需要展示base_rate、peroid、profit_margin这几个字段
        //根据 plan_mode判断
        //固定利率-0 （GW-A522501000 GW-A526889000 GW-A526847000)
        //浮动利率-1  （GW-A044749000 GW-A044837000 GW-A044860000）
        JSONObject resultData = jsonObject.getJSONObject("resultData");
        JSONArray repaymentPlan = resultData.getJSONArray("repayment_plan");
        if("0".equals(resultData.getString("plan_mode"))){
            resultData.remove("base_rate");
            resultData.remove("peroid");
            resultData.remove("profit_margin");
            //转换字符串
            resultData.put("loan_deadline",resultData.getString("loan_deadline"));
            for(int i=0;i<repaymentPlan.size();i++){
                JSONObject jb = repaymentPlan.getJSONObject(i);
                jb.remove("repayment_interest");
                jb.remove("settlement_amount");
                jb.remove("capital");
                jb.remove("identity");
                jb.remove("outstanding_principal");
                jb.remove("payment_month");
                jb.remove("outstanding_principal");
                jb.put("incidentals",jb.getString("incidentals"));
                jb.put("loan_peroid",jb.getString("loan_peroid"));
                jb.put("outstanding_capital",jb.getString("outstanding_capital"));
                jb.put("repayment_total_interest",jb.getString("repayment_total_interest"));
            }
        }else{
            resultData.put("peroid",0);
            resultData.put("loan_deadline",resultData.getString("loan_deadline"));
            resultData.put("base_rate",resultData.getString("base_rate"));
            resultData.remove("end_date");
            resultData.remove("finance_product");
            resultData.remove("payment_frequency");
            resultData.remove("start_date");
            resultData.remove("total_interest");
            resultData.remove("total_remain");
            resultData.remove("vehicle_desc");
            for(int i=0;i<repaymentPlan.size();i++){
                JSONObject jb = repaymentPlan.getJSONObject(i);
                jb.remove("actual_payment_amount");
                jb.remove("non_acceptance");
                jb.remove("outstanding_capital");
                jb.remove("payment_capital");
                jb.remove("repayment_total_interest");
                jb.remove("total_payment");

                jb.put("loan_peroid",jb.getString("loan_peroid"));
                jb.put("overdue_dd",jb.getString("overdue_dd"));
            }
        }
        jsonObject.put("resultData", com.alibaba.fastjson.JSON.toJSONString(jsonObject.get("resultData"), SerializerFeature.WriteMapNullValue));
    }

    /**
     * 获取客户信息
     * cms和icos同时都有返回时处理展示字段
     * @param jsonObject
     */
    private void customerProcessor(JSONObject jsonObject){

        JSONObject cmsResultData = jsonObject.getJSONObject("cms").getJSONObject("resultData");
        JSONObject bossResultData = jsonObject.getJSONObject("icos").getJSONObject("resultData");
        String cmsIdCard = cmsResultData.getString("id_card");
        String bossIdCard = bossResultData.getString("id_card");

        jsonObject.clear();
        jsonObject.put("timestamp","");
        jsonObject.put("signcode","");
        if (EmptyUtils.isNotEmpty(cmsIdCard) || EmptyUtils.isNotEmpty(bossIdCard)){
            jsonObject.put("resultCode", "0000");
            JSONObject resultData = JSONObject.parseObject("{}");
            if (EmptyUtils.isNotEmpty(cmsIdCard) && EmptyUtils.isNotEmpty(bossIdCard)){
                resultData.put("customer",bossResultData.getString("customer"));
                resultData.put("identity_user",bossResultData.getString("identity_user"));
                resultData.put("id_card",bossResultData.getString("id_card"));
                resultData.put("role",bossResultData.getString("role"));
                resultData.put("phone",bossResultData.getString("phone") + ","+cmsResultData.getString("phone"));
                JSONArray bossArray = bossResultData.getJSONArray("application");
                JSONArray cmsArray = cmsResultData.getJSONArray("application");
                bossArray.addAll(cmsArray);
                resultData.put("application",bossArray);
                resultData.put("loan_num",String.valueOf(bossArray.size()));
                jsonObject.put("resultData", com.alibaba.fastjson.JSON.toJSONString(resultData, SerializerFeature.WriteMapNullValue));
            }else if(EmptyUtils.isNotEmpty(cmsIdCard) && EmptyUtils.isEmpty(bossIdCard)){
                jsonObject.put("resultData", com.alibaba.fastjson.JSON.toJSONString(cmsResultData, SerializerFeature.WriteMapNullValue));
            }else{
                jsonObject.put("resultData", com.alibaba.fastjson.JSON.toJSONString(bossResultData, SerializerFeature.WriteMapNullValue));
            }
        }else{
            jsonObject.put("resultData", "");
            jsonObject.put("resultCode", "0001");
        }
    }

    /**
     * 获取客户详细信息
     * 将null结果转换为""
     * @param jsonObject
     */
    private void customerInfoProcessor(JSONObject jsonObject){
        JSONObject bossData = jsonObject.getJSONObject("icos");
        String bossCode = bossData.getString("resultCode");
        JSONObject bossResultData = com.alibaba.fastjson.JSON.parseObject(bossData.getString("resultData"));

        JSONObject cmsData = jsonObject.getJSONObject("cms");
        String cmsCode = cmsData.getString("resultCode");
        JSONObject cmsResultData = com.alibaba.fastjson.JSON.parseObject(cmsData.getString("resultData"));
        String resultCode = "9999";
        if("0000".equals(bossCode)&&EmptyUtils.isNotEmpty(bossResultData)){
            bossResultData = bossData.getJSONObject("resultData");
            resultCode="0000";
//            for(String key : bossResultData.keySet()){
//                if(bossResultData.get(key)==null){
//                    bossResultData.put(key,"");
//                }
//            }
        }

        if("0000".equals(cmsCode)&&EmptyUtils.isNotEmpty(cmsResultData)){
            cmsResultData = cmsData.getJSONObject("resultData");
            resultCode="0000";
//            for(String key : cmsResultData.keySet()){
//                if(cmsResultData.get(key)==null){
//                    cmsResultData.put(key,"");
//                }
//            }
        }
        //移除所有元素
        jsonObject.clear();
        String dataValue="未查询到任何数据";
        if(EmptyUtils.isNotEmpty(bossResultData)){
            dataValue = com.alibaba.fastjson.JSON.toJSONString(bossResultData, SerializerFeature.WriteMapNullValue);
        }else if(EmptyUtils.isNotEmpty(cmsResultData)){
            dataValue = com.alibaba.fastjson.JSON.toJSONString(cmsResultData, SerializerFeature.WriteMapNullValue);
        }

        //重新放入新的元素值
        jsonObject.put("resultCode",resultCode);
        jsonObject.put("resultData", dataValue);
        jsonObject.put("timestamp","");
        jsonObject.put("signcode","");
    }
}
